package com.gljx.web.controller;

import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.dao.ChangecoachthreeMapper;
import com.gljx.web.service.ChangecoachThreeService;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author lcx
 * @Date 2017/11/28 0028 上午 10:07
 * 科目二换教练
 */
@Controller
@RequestMapping("/")
public class ChangecoachThreeContraller {

    @Autowired
    ChangecoachThreeService changecoachThreeService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    CustomLogService customLogService;
    @Autowired
    ExerciseCarPlanController exerciseCarPlanController;
    @Autowired
    PersonController personController;
    @Autowired
    ChangecoachthreeMapper changecoachthreeMapper;

    /**
     * @Author lcx
     * @Date 2017/11/20 0020 上午 10:43
     * 查询科目三换教练
     */
    @RequestMapping("/queryChangecoachThree/look.action")
    public String queryChangecoachThree(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "fdescription", defaultValue = "") String fdescription
            , @RequestParam(value = "cfstudentname", defaultValue = "") String cfstudentname
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "") String endTime
            , @RequestParam(value = "state", defaultValue = "") String state
            , @RequestParam(value = "alertType", defaultValue = "") String alertType) {


        PageBean<Changecoachthree> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
            fnumber = fnumber.trim();//去空格
            fdescription = fdescription.trim();
            cfstudentname = cfstudentname.trim();
            //第一次进来
            if ("first".equals(state)) {
                beginTime = TimeFormat.getMonth();
                endTime = TimeFormat.getNowTime();
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, "");
            } else if ("".equals(state) && "".equals(beginTime) || "".equals(endTime)) {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, null);
            } else {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, fdescription, cfstudentname, beginTime, endTime, "");

            }
            //获取当前分页的值
            List<Changecoachthree> changecoachThreeList = pb.getBeanList();
            //把获取到的数据传回页面
            for (Changecoachthree changecoachThree : changecoachThreeList) {
                //查询学员信息
                changecoachThree.setChangecoachthreeentryList(changecoachThreeService.selectChangecoachThreeentryByFid(changecoachThree.getFid(), cfstudentname));
            }
            //合计信息总条数
            String messageAmount="共有"+pb.getTr()+"条信息";

            //返回界面的搜索条件
            request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("fdescription", fdescription);
            request.setAttribute("cfstudentname", cfstudentname);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);

            request.setAttribute("changecoachThreeList", changecoachThreeList);
            request.setAttribute("pb", pb);
            request.setAttribute("alertType", alertType);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/backHome/practiseCAR/ChangecoachThree/ChangecoachThreeList";
    }

    public PageBean<Changecoachthree> getPageBean(HttpServletRequest request, String companyId, String fnumber,
                                                  String fdescription, String cfstudentname,
                                                  String beginTime, String endTime,
                                                  String state) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
        if (state == null) {
            psql.append("SELECT DISTINCT c.fid," +
                    "  c.FNUMBER, " +
                    "  TO_CHAR(c.FBIZDATE, 'YYYY-MM-DD') FBIZDATE, " +
                    "  c.FDESCRIPTION," +
                    "   c.FCREATETIME, " +
                    "  u.NAME                            checkName, " +
                    "  u1.NAME                           createName,c.CFBILLSTATE, e.FNAME_L2 cflcsjidName " +
                    " FROM " +
                    "  CT_DS_CHANGECOACHTHREE c LEFT JOIN T_E_USER U ON c.FAUDITORID = u.FID " +
                    "  LEFT JOIN T_E_USER u1 ON c.FCREATORID = u1.FID " +
                    "   LEFT JOIN ct_ds_exercisecarplan e ON c.CFLCSJID = e.fid " +
                    " LEFT JOIN CT_DS_CHANGECOACHTHREEENTRY C2 ON C.FID = C2.FPARENTID" +
                    "  LEFT JOIN CT_DS_STUDENT S ON C2.CFSTUDENTID = S.FID" +
                    " where c.FCONTROLUNITID= '" + companyId + "'");
            if (!"".equals(fnumber)) {
                psql.append(" and C.FNUMBER LIKE '%" + fnumber + "%' ");
            }
            if (!"".equals(fdescription)) {
                psql.append(" and C.FDESCRIPTION LIKE '%" + fdescription + "%' ");
            }
            if (!"".equals(cfstudentname)) {
                psql.append(" and S.FNAME_L2 LIKE '%" + cfstudentname + "%' ");
            }
            psql.append(" ORDER BY c.FCREATETIME DESC");

        } else {
            psql.append("SELECT DISTINCT c.fid," +
                    "  c.FNUMBER, " +
                    "  TO_CHAR(c.FBIZDATE, 'YYYY-MM-DD') FBIZDATE, " +
                    "  c.FDESCRIPTION," +
                    "   c.FCREATETIME, " +
                    "  u.NAME                            checkName, " +
                    "  u1.NAME                           createName,c.CFBILLSTATE, e.FNAME_L2 cflcsjidName " +
                    " FROM " +
                    "  CT_DS_CHANGECOACHTHREE c LEFT JOIN T_E_USER U ON c.FAUDITORID = u.FID " +
                    "  LEFT JOIN T_E_USER u1 ON c.FCREATORID = u1.FID " +
                    "   LEFT JOIN ct_ds_exercisecarplan e ON c.CFLCSJID = e.fid " +
                    " LEFT JOIN CT_DS_CHANGECOACHTHREEENTRY C2 ON C.FID = C2.FPARENTID" +
                    "  LEFT JOIN CT_DS_STUDENT S ON C2.CFSTUDENTID = S.FID" +
                    " where c.FCONTROLUNITID= '" + companyId + "'");
            if (!"".equals(fnumber)) {
                psql.append(" and C.FNUMBER LIKE '%" + fnumber + "%' ");
            }
            if (!"".equals(fdescription)) {
                psql.append(" and C.FDESCRIPTION LIKE '%" + fdescription + "%' ");
            }
            if (!"".equals(cfstudentname)) {
                psql.append(" and S.FNAME_L2 LIKE '%" + cfstudentname + "%' ");
            }
            psql.append(" AND (c.FBIZDATE BETWEEN to_date('" + beginTime + "', 'YYYY/MM/DD') AND to_date('" + endTime + "', 'YYYY/MM/DD')) ORDER BY c.FCREATETIME DESC");
        }

        int psize = 100; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = changecoachThreeService.selectPage(pindex, psql.toString(), psize);
        PageBean<Changecoachthree> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<Changecoachthree>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }

    /**
     * 取记录总数 dmz 20160921
     *
     * @param psql SQL语句
     * @return Map
     * @throws Exception
     */
    public Map<String, Object> getPageBeanCount(String psql) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = changecoachThreeService.selectPageCount(psql);
        return paramMap;
    }

    /**
     * @Author lcx
     * @Date 2017/11/28 0028 上午 11:26
     * 添加换教练
     */
    @RequestMapping(value = "/go_add_ChangecoachThree")
    public String goAddChangecoachThree(HttpServletRequest request, String alertType) throws Exception {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        /* String number = customLogService.selectFunmber("CT_DS_CHANGECOACHTHREE", user.getFcompanyid());*/
        String fnumber = GetFnumber.fnumbers("KMSHJL");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String fbizdate = sdf.format(new Date());

        //查询练车时间
        Map map3 = exerciseCarPlanController.getExerciseCarPlan(request, "", "", "0");
        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");

        request.setAttribute("fbizdate", fbizdate);
        request.setAttribute("createName", user.getName());
        request.setAttribute("fnumber", fnumber);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb3", map3.get("pb"));
        request.setAttribute("exerciseCarPlans", map3.get("sList"));
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
        request.setAttribute("alertType", alertType);



        return "/backHome/practiseCAR/ChangecoachThree/ChangecoachThreeAdd";

    }

    /**
     * @Author lcx
     * @Date 2017/11/28 0028 下午 2:04
     * 添加
     */
    @RequestMapping(value = "/add_changecoachThree")
    public String addChangecoachThreeReg(HttpServletRequest request, Changecoachthree changecoachthree, @RequestParam(defaultValue = "0") String state) {

        //获取操作人信息t
        User user = (User) request.getSession().getAttribute("user");
        //公司id
        changecoachthree.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        changecoachthree.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //创建时间
        changecoachthree.setFcreatetime(createTime);
        //创建人id
        changecoachthree.setFcreatorid(user.getFid());


        //获取子类
        String[] cfstudentid = request.getParameterValues("cfstudentid");//学生id
        String[] cfstudentno = request.getParameterValues("cfstudentno");
        String[] cfmobile = request.getParameterValues("cfmobile");
        String[] cfphone = request.getParameterValues("cfphone");
        String[] cfcoachid2 = request.getParameterValues("cfcoachid2");//原教练id
        String[] cfcoachid = request.getParameterValues("cfcoachid");//现在教练id
        String[] cfcoachno = request.getParameterValues("cfcoachno");//现在教练编号
        String[] cfremark = request.getParameterValues("cfremark");

        changecoachThreeService.addChangecoachThree(changecoachthree, cfstudentid, cfstudentno,
                cfmobile, cfphone, cfcoachid2, cfcoachid, cfcoachno, cfremark, state);


        //添加日志
        customLogService.addLog("练车管理", TimeFormat.timeFormat(new Date()) + "对科目二换教练新增", null, user.getFid());


        return "redirect:/DrivingSys/go_add_ChangecoachThree?alertType=bc";
    }


    @RequestMapping(value = "go_update_changecoachThree")
    public String goUpdateShareCarThreeReg(HttpServletRequest request, String fid, String xqid) throws Exception {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        //查询换教练
        Changecoachthree changecoachThreeList = changecoachThreeService.selectChangecoachThreeByFid(fid);

        if (changecoachThreeList == null) {
            return "/error/not_data";
        }

        //查询练车时间
        Map map3 = exerciseCarPlanController.getExerciseCarPlan(request, "", "", "0");
        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");

        //查询是否是经办人
        Axamine axamine = new Axamine();
        request.setAttribute("AuditState", axamine.selectAuditPerson(changecoachThreeList.getFnumber()));

        request.setAttribute("changecoachThreeList", changecoachThreeList);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb3", map3.get("pb"));
        request.setAttribute("exerciseCarPlans", map3.get("sList"));
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));

        return "/backHome/practiseCAR/ChangecoachThree/updateChangecoachThree";
    }

    /**
     * @Author lcx
     * @Date 2017/11/28 0028 下午 3:53
     * 更新
     */
    @RequestMapping(value = "/update_changecoachThree")
    public String updateRecordin(HttpServletRequest request, Changecoachthree changecoachthree) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //修改时间
        changecoachthree.setFlastupdatetime(createTime);
        //修改人id
        changecoachthree.setFlastupdateuserid(user.getFid());

        addChangecoachThreeReg(request, changecoachthree, "1");

        return "redirect:/DrivingSys/queryChangecoachThree/look.action?state=first&alertType=qd";
    }

    /**
     * @Author lcx
     * @Date 2017/11/29 0029 下午 3:26
     * 删除
     */
    @RequestMapping(value = "delete_changecoachThree")
    public String deleteChangecoachThree(HttpServletRequest request, String[] deleteId, String[] fnumber) throws Exception {

        User user = (User) request.getSession().getAttribute("user");

        changecoachThreeService.deleteByChangecoachThreeKey(deleteId, fnumber);
        //添加日志
        customLogService.addLog("练车管理", TimeFormat.timeFormat(new Date()) + "对科目二换教练进行删除", null, user.getFid());


        return "redirect:/DrivingSys/queryChangecoachThree/look.action?state=first";
    }

    /**
     * @Author lcx
     * @Date 2018/2/6 0006 上午 11:02
     */
    @RequestMapping(value = "/queryChangecoachThreeExamine")
    @ResponseBody
    public ServerResponse examine(HttpServletRequest request, @RequestParam(defaultValue = "", value = "fid") String fid,
                                  @RequestParam(defaultValue = "", value = "state") String state,
                                  @RequestParam(defaultValue = "", value = "agreed") String agreed,
                                  @RequestParam(defaultValue = "", value = "auditcomment") String auditcomment,
                                  @RequestParam(defaultValue = "", value = "fnumber") String fnumber) {
        Changecoachthree changecoachthree = new Changecoachthree();

        changecoachthree.setFid(fid);
        changecoachthree.setFnumber(fnumber);

        return changecoachThreeService.examine(changecoachthree, state, agreed, auditcomment);
    }

    /**
     * @Author lcx
     * @Date 2018/2/27 0027 上午 11:49
     * 提交
     */
    @RequestMapping(value = "/queryChangecoachThreeSubmit")
    @ResponseBody
    public ServerResponse submit(HttpServletRequest request,
                                 @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                 @RequestParam(defaultValue = "", value = "fid") String fid) {
        Axamine axamine = new Axamine();
        Changecoachthree changecoachthree = new Changecoachthree();

        changecoachthree.setFid(fid);
        /*changecoachthree.setFauditorid(((User) request.getSession().getAttribute("user")).getFid());*/
        changecoachthree.setCfbillstate(Long.valueOf("4"));
        changecoachthreeMapper.updateByPrimaryKeySelective(changecoachthree);
        return axamine.submissionProcess(String.valueOf(fnumber));
    }

    @RequestMapping("/queryChangecoachThreeRegXls")
    public String queryChangecoachThreeRegXls(HttpServletRequest request, HttpServletResponse response,
                                              @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                              @RequestParam(defaultValue = "", value = "fdescription") String fdescription,
                                              @RequestParam(defaultValue = "", value = "cfstudentname") String cfstudentname,
                                              @RequestParam(defaultValue = "", value = "beginTime") String beginTime,
                                              @RequestParam(defaultValue = "", value = "endTime") String endTime) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //头部数据
        List<Object> data = new ArrayList<>();
        String head[] = {"单据编号", "业务日期", "参考消息", "审核人名称", "制单人名称", "单据状态", "练车时间", "学员", "学员编号", "手机",
                "电话", "教练", "教练编码", "备注", "当前教练"
        };
        //长度
        Integer length[] = {8500, 5000, 6000, 3000, 3000, 3000, 9000, 3000, 6000, 4000,
                4000, 3000, 3000, 6000, 3000};

        List<Changecoachthreeentry> changecoachthreeentryList = changecoachThreeService.selectChangecoachThreeregAsXls(fnumber, fdescription, cfstudentname, beginTime, endTime, user.getFcompanyid());


        for (Changecoachthreeentry changecoachthreeentry : changecoachthreeentryList) {
            data.add(changecoachthreeentry.getFnumber());
            data.add(changecoachthreeentry.getFbizdate());
            data.add(changecoachthreeentry.getFdescription());
            data.add(changecoachthreeentry.getCheckName());
            data.add(changecoachthreeentry.getCreateName());
            data.add(stateToString.billsState(changecoachthreeentry.getCfbillstate()));
            data.add(changecoachthreeentry.getCflcsjidName());//练车时间
            data.add(changecoachthreeentry.getCfstudentName());
            data.add(changecoachthreeentry.getCfstudentno());
            data.add(changecoachthreeentry.getCfmobile());
            data.add(changecoachthreeentry.getCfphone());
            data.add(changecoachthreeentry.getCfcoachName());
            data.add(changecoachthreeentry.getCfcoachno());//教练编码
            data.add(changecoachthreeentry.getCfremark());//备注
            data.add(changecoachthreeentry.getCfcoachName2());//当前教练
        }

        try {
            //导出Excel
            CommonExport.importExcel(response, "科目三换教练" + TimeFormat.getNowTime2() + ".xls", "科目三换教练", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/DrivingSys/queryChangecoachTwo/look.action?state=first";
    }
}
